package edu.neusoft.springmvc.controller;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import edu.neusoft.springmvc.model.TestModel;
import edu.neusoft.springmvc.model.User;

@Controller
@RequestMapping("/testsession")
@SessionAttributes(value = "testModel")
public class SessionController {

  @ModelAttribute("testModel")
  public TestModel getTestModel() {
    return new TestModel("111", "222", "333", "444");
  }

  @RequestMapping("/totestmodel")
  public ModelAndView toTestModel(ModelAndView mv, HttpSession session) {
    mv.setViewName("redirect:/testsession/dotest");
    return mv;
  }

  @RequestMapping(value = "dotest", method = { RequestMethod.GET, RequestMethod.POST })
  public String doTestModel(ModelMap map, HttpSession session) {
    TestModel model1 = (TestModel) map.get("testModel");
    TestModel model2 = (TestModel) session.getAttribute("testModel");
    System.out.println(model1.getStr1() + "-" + model1.getStr2() + model1.getStr3() + "-" + model1.getStr4());
    System.out.println(model2.getStr1() + "-" + model2.getStr2() + model2.getStr3() + "-" + model2.getStr4());
    return "success";
  }

  @ModelAttribute("user")
  public User getUser() {
    User user = new User();
    /* user.setUsername("zhangsan");
    user.setPasword("password");*/
    user.setAge("35");
    return user;
  }

  //http://localhost:8080/spring01/testsession/modelattribute
  //http://localhost:8080/spring01/testsession/
  //modelattribute?username=lisi&password=helloworld
  @RequestMapping(value = "modelattribute", method = { RequestMethod.GET, RequestMethod.POST })
  public ModelAndView testModelAttribute(@ModelAttribute("user") User user, ModelAndView mv) {
    mv.setViewName("redirect:/testsession/test1");
    /* System.out.println(user.getUsername() + "-" + user.getPasword() + "-" + user.getAge());*/
    return mv;
  }

  @RequestMapping(value = "test1", method = { RequestMethod.GET, RequestMethod.POST })
  public String test1(ModelMap map) {
    User user = (User) map.get("user");
    /* System.out.println(user.getUsername() + "-" + user.getPasword() + "-" + user.getAge());*/
    return "success";
  }

}
